package com.heng.apphook.hook;

import android.content.Context;

import com.heng.apphook.utils.LocationPreferences;
import com.heng.mapbundle2.MockLocationV2;
import com.heng.mapbundle2.MyLocation;
import com.swift.sandhook.annotation.HookClass;
import com.swift.sandhook.annotation.HookMethod;
import com.swift.sandhook.annotation.HookMethodBackup;
import com.swift.sandhook.annotation.ThisObject;

import java.lang.reflect.Method;

/**
 * @Author : zhangheng227
 * date       : 2025/5/23
 */
@HookClass(MockLocationV2.class)
public class MockLocationHooker {
    @HookMethodBackup("getLocation")
    static Method getLocationBackup;

    @HookMethod("getLocation")
    public static MyLocation getLocationHook(@ThisObject MockLocationV2 thiz) {
        Context context = MockLocationV2.getApplicationContext();
        if (context == null){
            try {
                return (MyLocation)getLocationBackup.invoke(thiz);
            } catch (Throwable e) {
                // 异常处理，返回 null 或根据需求调整
                return null;
            }
        }
        boolean enabled = LocationPreferences.Companion.isMockEnabled(context);
        if (enabled) {
            // 时间戳是奇数，返回新的 MyLocation 实例
            MyLocation savedLocation = LocationPreferences.Companion.getSavedLocation(context);
            if (savedLocation != null){
                return savedLocation;
            }else {
                try {
                    return (MyLocation)getLocationBackup.invoke(thiz);
                } catch (Throwable e) {
                    // 异常处理，返回 null 或根据需求调整
                    return null;
                }
            }
        } else {
            // 时间戳是偶数，调用原始方法
            try {
                return (MyLocation)getLocationBackup.invoke(thiz);
            } catch (Throwable e) {
                // 异常处理，返回 null 或根据需求调整
                return null;
            }
        }
    }
}
